package com.delivery.www.dao.DaoImpl;

import com.delivery.www.dao.MessageDao;
import com.delivery.www.po.Message;
import com.delivery.www.util.JdbcUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MessageDaoImpl implements MessageDao {
    @Override
    public List<Message> getMessage(int storeId) {
        Connection connection = JdbcUtils.getConnection();
        List<Message> messages = new ArrayList<>();
        PreparedStatement pstm = null;
        ResultSet rs = null;
        Object[] params = {storeId};
        String sql = "select m.message_id,content from message m where store_id = ?";
        rs = JdbcUtils.excute(connection, pstm, rs, sql, params);
        try {
            while (rs.next()) {
                Message message = new Message();
                message.setMessageId(rs.getInt("message_id"));
                message.setContent(rs.getString("content"));
                messages.add(message);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        JdbcUtils.closeResource(connection, pstm, rs);
        return messages;
    }

    @Override
    public int doMessage(int storeId, String content) {
        Connection connection = JdbcUtils.getConnection();
        PreparedStatement pstm = null;
        Object[] params = {storeId, content};
        String sql = "insert into message (store_id,content) values(?,?)";
        int excute = JdbcUtils.excute(connection, pstm, sql, params);
        JdbcUtils.closeResource(connection, pstm, null);
        return excute;
    }

    @Override
    public int deleteMessage(int messageId) {
        Connection connection = JdbcUtils.getConnection();
        PreparedStatement pstm = null;
        Object[] params = {messageId};
        String sql = "delete from message where message_id = ?";
        int excute = JdbcUtils.excute(connection, pstm, sql, params);
        JdbcUtils.closeResource(connection, pstm, null);
        return excute;
    }
}
